/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Service;

import PIServer.VMSProtocolHandler;
import java.util.Hashtable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.mina.core.session.IoSession;
import Utility.Memcache;
import com.sun.net.httpserver.Headers;
import PIServer.Main;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author anlh
 */
public class AdminService {

    public static final Logger log = LoggerFactory.getLogger(AdminService.class.getName());
    public static Hashtable<String, String> messageList = new Hashtable<String, String>();

//KICK USER FUNCTION
    public int kickUser(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
        try {

            String userBeKick = requestHeaders.getFirst("username");
            if (userBeKick == null) {
                log.info("Kick user failed ! Missing username !");
                responseHeaders.set("Result", "Missing username !");
                return HttpResponseConstant.HTTP_RESPONSE_BAD_REQUEST;
            }
            IoSession userSession = VMSProtocolHandler.getSessionByUserName(userBeKick);
            log.info(userBeKick);
            if (userSession == null) {
                log.info("Kick user failed ! User not found !");
                responseHeaders.set("Result", "User not found !");
                result = HttpResponseConstant.HTTP_RESPONSE_NOT_FOUND;
            } else {
                ServerService.kick(userBeKick);
                log.info("USER HAS BEEN KICKED !");
                responseHeaders.set("Result", "Done !");
            }
        } catch (Exception ex) {
            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
            log.error(ex.getClass().getName(), ex);
        }
        return result;
    }

    //BROADCAST MESS FROM ADMIN
    public int broadcastAdminMessage(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
//        try {
//            //ADD ADMIN'S MESSAGE TO FIRST PLACE IN BROADCAST MESS QUEUE
//            //String broadcastMess = new String(requestHeaders.getFirst("message").getBytes("UTF-8"), "UTF-8");
//            String tmpMessage = requestHeaders.getFirst("message");
//            if (tmpMessage == null) {
//                log.info("Broadcast faild ! Missing broadcast message");
//                responseHeaders.set("Result", "Missing Message !");
//                return HttpResponseConstant.HTTP_RESPONSE_BAD_REQUEST;
//            }
//            String broadcastMess = URLDecoder.decode(tmpMessage, "UTF-8");
//            log.info(broadcastMess);
//            int service = ItemService.BROADCAST_ALL_SYSTEM;
//            String serviceString = requestHeaders.getFirst("service");
//            if (serviceString != null) {
//                service = Integer.parseInt(serviceString);
//            }
//            int loopTimes = 1;
//            String loopString = requestHeaders.getFirst("loop");
//            if (loopString != null && service == 0) {
//                loopTimes = Integer.parseInt(loopString);
//            }
//
//            while (loopTimes > 0) {
//                ItemFeatureService.addBroadcastMessage(broadcastMess, ItemService.HIGH_PRIORITY, service);
//                loopTimes--;
//            }
//            log.info("ANNOUCEMENT HAS BEEN POSTED  !!!!!!!!!!!!!!!");  //for debug
//            responseHeaders.set("Result", "Done !");
//
//        } catch (Exception ex) {
//            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
//            log.error(ex.getClass().getName(), ex);
//        }
        return result;
    }

    //GET USERINFO AND SEND TO ADMIN
    public int sendUserInfo(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
        try {
            String user = requestHeaders.getFirst("username");
            if (user == null) {
                log.info("Get user failed ! Missing username !");
                responseHeaders.set("Result", "Missing username !");
                return HttpResponseConstant.HTTP_RESPONSE_BAD_REQUEST;
            }
            IoSession userSession = VMSProtocolHandler.getSessionByUserName(user);
            if (userSession == null) {
                log.info("Get user failed ! User not found !");
                responseHeaders.set("Result", "User not found !");
                result = HttpResponseConstant.HTTP_RESPONSE_NOT_FOUND;
            } else {
                String userRoom = (String) userSession.getAttribute("room");
                if (userRoom == null) {
                    userRoom = "User not enter any room yet !";
                }
                String userTable = (String) userSession.getAttribute("table");
                if (userTable == null) {
                    userTable = "User not enter any table yet !";
                }
                responseHeaders.set("X-Room", userRoom);
                responseHeaders.set("X-Table", userTable);
                log.info("User info sent !");
            }
        } catch (Exception ex) {
            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
            log.error(ex.getClass().getName(), ex);
        }
        return result;
    }

    public int sendNumberUserOnline(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
        try {
            int numberUserOnline = 0;
            int numberTienLenPlayer = 0;
            int numberBinhPlayer = 0;
            int numberBattleshipPlayer = 0;
            int numberPhomPlayer = 0;
            synchronized (VMSProtocolHandler.clientSessions.values()) {
                Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
                while (iter.hasNext()) {
                    IoSession s = (IoSession) iter.next();
                    String username = (String) s.getAttribute("user");
                    if (username != null) {
                        numberUserOnline++;
//                        responseHeaders.set(numberUserOnline + "", username);
                    }
                    if (s.getAttribute("table") != null) {
                        String tableID = (String) s.getAttribute("table");
                        if (tableID.startsWith("TL")) {
                            numberTienLenPlayer++;
                        } else if (tableID.startsWith("TB")) {
                            numberBinhPlayer++;
                        } else if (tableID.startsWith("BS")) {
                            numberBattleshipPlayer++;
                        }
                    }
                }
            }
//            ResetTimeTask.removeIdlePhomPlayer();
            ArrayList<String> PhomPlayer = new ArrayList<String>();
            if (Memcache.getInstance().get("PhomPlayer") != null) {
                PhomPlayer = (ArrayList<String>) Memcache.getInstance().get("PhomPlayer");
            }
            if (PhomPlayer != null) {
                numberPhomPlayer = PhomPlayer.size();
            }
            responseHeaders.set("totalNumber", numberUserOnline + "");
            responseHeaders.set("TL", numberTienLenPlayer + "");
            responseHeaders.set("TB", numberBinhPlayer + "");
            responseHeaders.set("BS", numberBattleshipPlayer + "");
            responseHeaders.set("PH", numberPhomPlayer + "");

        } catch (Exception ex) {
            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
            log.error(ex.getClass().getName(), ex);
        }
        return result;
    }

    public int sendListUserOnline(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
        try {
            int numberUserOnline = 0;
            synchronized (VMSProtocolHandler.clientSessions.values()) {
                Iterator<IoSession> iter = VMSProtocolHandler.clientSessions.values().iterator();
                while (iter.hasNext()) {
                    IoSession s = (IoSession) iter.next();
                    String username = (String) s.getAttribute("user");
                    if (username != null) {
                        numberUserOnline++;
                        responseHeaders.set(numberUserOnline + "", username);
                    }
                }
            }
            responseHeaders.set("totalNumber", numberUserOnline + "");
        } catch (Exception ex) {
            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
            log.error(ex.getClass().getName(), ex);
        }
        return result;
    }

    public int sendBroadcastList(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
//        try {
//            int numberMessage = 0;
//            //String[] tmpList = ItemFeatureService.messQueue.toArray(new String[0]);
//
//            Iterator<ArrayList> iter = ItemFeatureService.messQueue.iterator();
//            while (iter.hasNext()) {
//                ArrayList mess = (ArrayList) iter.next();
//                if (mess != null) {
//                    numberMessage++;
//                    responseHeaders.set(numberMessage + "", (String) mess.get(0));
//                }
//            }
//            responseHeaders.set("totalNumber", numberMessage + "");
//        } catch (Exception ex) {
//            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
//            log.error(ex.getClass().getName(), ex);
//        }
        return result;
    }

    public int updateNews(Headers requestHeaders, Headers responseHeaders,
            OutputStream responseBody) {

        int result = HttpResponseConstant.HTTP_RESPONSE_OK;
//        if (!NewsService.getNewsList()) {
//            result = HttpResponseConstant.HTTP_RESPONSE_INTERNAL_SERVER_ERROR;
//        }

        return result;
    }

    //////////////GET PARAMETER FUNCTION ///////////////////
    public void getKickUserParameter(String strMessage) {
        if (strMessage.startsWith("username")) {
            String tmpMessage = strMessage.substring(strMessage.indexOf(" ") + 1);
            log.info("username get =" + tmpMessage);
            AdminService.messageList.put("username", tmpMessage);
        }
    }

    public void getBroadcastParameter(String strMessage) {
        try {
            if (strMessage.startsWith("message")) {
                String tmpMessage = strMessage.substring(strMessage.indexOf(" ") + 1);
                String result = new String(tmpMessage.getBytes("UTF-8"), "UTF-8");
                log.info("message get =" + result);
                AdminService.messageList.put("message", result);
            }
            if (strMessage.startsWith("loop")) {
                String tmpMessage = strMessage.substring(strMessage.indexOf(" ") + 1);
                log.info("LOOP TIMES =" + tmpMessage);
                AdminService.messageList.put("loop", tmpMessage);
            }
        } catch (Exception ex) {
            log.error(ex.getClass().getName(), ex);
        }

    }

    public void getInfoUserParameter(String strMessage) {
        if (strMessage.startsWith("username")) {
            String tmpMessage = strMessage.substring(strMessage.indexOf(" ") + 1);
            log.info("user get =" + tmpMessage);
            AdminService.messageList.put("username", tmpMessage);
        }
    }

//    public int restartServer(Headers requestHeaders, Headers responseHeaders, OutputStream responseBody) {
//        VMServer.restartServer();
//        return HttpResponseConstant.HTTP_RESPONSE_OK;
//    }

    public int shutdownServer(Headers requestHeaders, Headers responseHeaders, OutputStream responseBody) {
        Main.shutdownServer();
        return HttpResponseConstant.HTTP_RESPONSE_OK;
    }
}
